<div class="box">
    <div class="box-header with-border">
        <h3 class="box-title">商品批量导入</h3>
        <div class="box-tools pull-right">
            <a href="{:url('downloadTemplate')}" class="btn btn-success btn-sm">
                <i class="fa fa-download"></i> 下载导入模板
            </a>
            <a href="{:url('productList')}" class="btn btn-default btn-sm">
                <i class="fa fa-arrow-left"></i> 返回列表
            </a>
        </div>
    </div>
    
    <div class="box-body">
        <!-- 导入说明 -->
        <div class="alert alert-info">
            <h4><i class="icon fa fa-info"></i> 导入说明</h4>
            <ul>
                <li>请先下载导入模板，按照模板格式填写商品信息</li>
                <li>支持Excel格式文件（.xls, .xlsx），文件大小不超过10MB</li>
                <li>必填字段：商品名称、分类、现价</li>
                <li>价格字段请填写数字，状态字段请填写"启用"或"禁用"</li>
                <li>VIP专享字段请填写"是"或"否"</li>
                <li>系统会自动验证数据格式，只有验证通过的数据才会被导入</li>
            </ul>
        </div>
        
        <!-- 导入表单 -->
        <form action="{:url()}" method="post" enctype="multipart/form-data" class="form_single">
            <div class="row">
                <div class="col-md-8">
                    <div class="form-group">
                        <label>选择Excel文件</label>
                        <input type="file" name="import_file" class="form-control" accept=".xls,.xlsx" required>
                        <small class="help-block">支持.xls和.xlsx格式，文件大小不超过10MB</small>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label>&nbsp;</label>
                        <div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fa fa-upload"></i> 开始导入
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 导入历史记录 -->
<div class="box">
    <div class="box-header with-border">
        <h3 class="box-title">导入历史记录</h3>
    </div>
    
    <div class="box-body">
        {if condition="!empty($importLogs.data)"}
        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>批次ID</th>
                        <th>文件名</th>
                        <th>文件大小</th>
                        <th>总行数</th>
                        <th>成功数</th>
                        <th>失败数</th>
                        <th>成功率</th>
                        <th>状态</th>
                        <th>操作人</th>
                        <th>导入时间</th>
                        <th>耗时</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {volist name="importLogs.data" id="log"}
                    <tr>
                        <td>{$log.batch_id}</td>
                        <td title="{$log.filename}">{$log.filename|mb_substr=0,20,'utf-8'}...</td>
                        <td>{$log.file_size_text}</td>
                        <td>{$log.total_rows|default=0}</td>
                        <td class="text-success">{$log.success_rows|default=0}</td>
                        <td class="text-danger">{$log.failed_rows|default=0}</td>
                        <td>{$log.success_rate_text}</td>
                        <td>
                            {switch name="log.import_status"}
                                {case value="processing"}
                                    <span class="label label-warning">处理中</span>
                                {/case}
                                {case value="completed"}
                                    <span class="label label-success">已完成</span>
                                {/case}
                                {case value="failed"}
                                    <span class="label label-danger">失败</span>
                                {/case}
                                {default /}
                                    <span class="label label-default">未知</span>
                            {/switch}
                        </td>
                        <td>{$log.operator_name}</td>
                        <td>{$log.create_time_text}</td>
                        <td>{$log.duration_text}</td>
                        <td>
                            <button type="button" class="btn btn-xs btn-info" onclick="viewImportDetail('{$log.batch_id}')">
                                <i class="fa fa-eye"></i> 查看详情
                            </button>
                            {if condition="$log.import_status == 'failed' && !empty($log.error_message)"}
                            <button type="button" class="btn btn-xs btn-warning" onclick="viewErrorMessage('{$log.error_message}')">
                                <i class="fa fa-exclamation-triangle"></i> 错误信息
                            </button>
                            {/if}
                        </td>
                    </tr>
                    {/volist}
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        {if condition="!empty($importLogs.last_page) && $importLogs.last_page > 1"}
        <div class="box-footer clearfix">
            <ul class="pagination pagination-sm no-margin pull-right">
                {if condition="$importLogs.current_page > 1"}
                <li><a href="?page={$importLogs.current_page - 1}">&laquo;</a></li>
                {/if}
                
                {for start="1" end="$importLogs.last_page + 1"}
                <li {if condition="$i == $importLogs.current_page"}class="active"{/if}>
                    <a href="?page={$i}">{$i}</a>
                </li>
                {/for}
                
                {if condition="$importLogs.current_page < $importLogs.last_page"}
                <li><a href="?page={$importLogs.current_page + 1}">&raquo;</a></li>
                {/if}
            </ul>
        </div>
        {/if}
        
        {else /}
        <div class="text-center text-muted">
            <p>暂无导入记录</p>
        </div>
        {/if}
    </div>
</div>

<!-- 导入详情模态框 -->
<div class="modal fade" id="importDetailModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">导入详情</h4>
            </div>
            <div class="modal-body">
                <div id="importDetailContent">
                    <div class="text-center">
                        <i class="fa fa-spinner fa-spin"></i> 加载中...
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
$(function() {
    // 文件选择验证
    $('input[name="import_file"]').change(function() {
        var file = this.files[0];
        if (file) {
            // 验证文件类型
            var allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
            if (allowedTypes.indexOf(file.type) === -1) {
                layer.msg('请选择Excel文件（.xls或.xlsx格式）', {icon: 2});
                $(this).val('');
                return;
            }
            
            // 验证文件大小（10MB）
            if (file.size > 10 * 1024 * 1024) {
                layer.msg('文件大小不能超过10MB', {icon: 2});
                $(this).val('');
                return;
            }
        }
    });
    
    // 表单提交验证
    $('.form_single').submit(function() {
        var file = $('input[name="import_file"]')[0].files[0];
        if (!file) {
            layer.msg('请选择要导入的Excel文件', {icon: 2});
            return false;
        }
        
        // 显示加载提示
        var loadingIndex = layer.load(1, {
            shade: [0.3, '#000']
        });
        
        // 设置超时关闭加载提示
        setTimeout(function() {
            layer.close(loadingIndex);
        }, 30000);
        
        return true;
    });
});

/**
 * 查看导入详情
 */
function viewImportDetail(batchId) {
    $('#importDetailModal').modal('show');
    
    $.ajax({
        url: '{:url("getImportDetail")}',
        type: 'POST',
        data: {batch_id: batchId},
        dataType: 'json',
        success: function(response) {
            if (response.code == 1) {
                var html = buildDetailTable(response.data);
                $('#importDetailContent').html(html);
            } else {
                $('#importDetailContent').html('<div class="alert alert-danger">' + (response.msg || '获取详情失败') + '</div>');
            }
        },
        error: function() {
            $('#importDetailContent').html('<div class="alert alert-danger">网络错误，获取详情失败</div>');
        }
    });
}

/**
 * 构建详情表格
 */
function buildDetailTable(data) {
    if (!data || data.length === 0) {
        return '<div class="text-center text-muted">暂无详情数据</div>';
    }
    
    var html = '<div class="table-responsive">';
    html += '<table class="table table-bordered table-striped table-condensed">';
    html += '<thead>';
    html += '<tr>';
    html += '<th>行号</th>';
    html += '<th>商品名称</th>';
    html += '<th>分类</th>';
    html += '<th>品牌</th>';
    html += '<th>现价</th>';
    html += '<th>验证状态</th>';
    html += '<th>导入状态</th>';
    html += '<th>错误信息</th>';
    html += '</tr>';
    html += '</thead>';
    html += '<tbody>';
    
    $.each(data, function(index, item) {
        html += '<tr>';
        html += '<td>' + item.row_number + '</td>';
        html += '<td>' + (item.name || '') + '</td>';
        html += '<td>' + (item.category || '') + '</td>';
        html += '<td>' + (item.brand || '') + '</td>';
        html += '<td>' + (item.current_price || 0) + '</td>';
        html += '<td>';
        if (item.validation_status === 'valid') {
            html += '<span class="label label-success">验证通过</span>';
        } else {
            html += '<span class="label label-danger">验证失败</span>';
        }
        html += '</td>';
        html += '<td>';
        if (item.import_status === 'success') {
            html += '<span class="label label-success">导入成功</span>';
        } else if (item.import_status === 'failed') {
            html += '<span class="label label-danger">导入失败</span>';
        } else {
            html += '<span class="label label-default">待导入</span>';
        }
        html += '</td>';
        html += '<td>';
        var errorMsg = item.validation_message || item.import_message || '';
        if (errorMsg) {
            html += '<span class="text-danger" title="' + errorMsg + '">' + 
                    (errorMsg.length > 20 ? errorMsg.substring(0, 20) + '...' : errorMsg) + '</span>';
        }
        html += '</td>';
        html += '</tr>';
    });
    
    html += '</tbody>';
    html += '</table>';
    html += '</div>';
    
    return html;
}

/**
 * 查看错误信息
 */
function viewErrorMessage(errorMessage) {
    layer.alert(errorMessage, {
        title: '错误信息',
        icon: 2,
        area: ['500px', '300px']
    });
}
</script>